package concurrent;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * TODO 简单说明
 *
 * @author yangyang
 * @date 2017/7/25 11:14
 * @email kekecany@163.com
 */
class TaskPortion implements Runnable {

    private static int counter = 0;
    private int id = counter++;
    private CountDownLatch countDownLatch;
    private static Random random = new Random(47);

    TaskPortion(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        try {
            doWork();
            countDownLatch.countDown();
        }catch (InterruptedException e) {
            System.out.println(this + " interrupt, acceptable way to exit");
        }

    }

    private void doWork() throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(random.nextInt(2000));
        System.out.println(this + " completed");
    }

    @Override
    public String toString() {
        return String.format("%1$-3d", id);
    }
}

class WaitingTask implements Runnable {

    private static int counter = 0;
    private int id = counter++;
    private CountDownLatch countDownLatch;
    private Random random = new Random(47);

    WaitingTask(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        try {
            countDownLatch.await();
            System.out.println("latch barrier passed for " + this);
        } catch (InterruptedException e) {
            System.out.println(this + "interrupted");
        }
    }

    @Override
    public String toString() {
        return String.format("waitingTask %1$-3d", id);
    }
}

public class CountDownLatchDemo {

    private static final int SIZE = 100;
    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(SIZE);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            executorService.execute(new WaitingTask(countDownLatch));
        }
        for (int i = 0; i < SIZE; i++) {
            executorService.execute(new TaskPortion(countDownLatch));
        }
        System.out.println("launched all tasks");
        executorService.shutdown();
    }

}